package com.yt.fras.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.yt.fras.pojo.base.UserInputExcel;
import com.yt.fras.service.ExcelService;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * ClassName:ExcelListener
 * Package:com.yt.fras.listener
 * Description:
 * 模板的读取类
 *
 * @date:2021/11/15 0:10
 * @author:yt
 */
@Slf4j
public class ExcelListener implements ReadListener<UserInputExcel> {

    /**
     * 每隔100条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    private List<UserInputExcel> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    /**
     * 假设这个是一个DAO，当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
     */

    private ExcelService excelService;

    private String groupId;


    public ExcelListener(ExcelService excelService, String groupId) {
        this.excelService = excelService;
        this.groupId = groupId;
    }

    @Override
    public void invoke(UserInputExcel userInputExcel, AnalysisContext analysisContext) {
        cachedDataList.add(userInputExcel);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        excelService.addGroupUsers(cachedDataList, groupId);
        log.info("存储数据库成功！");
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }
}
